package com.topdt.jbpm.service.impl;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thx.common.spring.BeanFactory;
import com.topdt.jbpm.identity.IdFactory;
import com.topdt.jbpm.identity.IdentityService;
import com.topdt.jbpm.identity.User;
import com.topdt.jbpm.model.SendMessage;
import com.topdt.jbpm.service.SendMailService;


/**
 *  @Project       : thx-workflow
 *  @Program Name  : com.topdt.jbpm.service.impl.SendMailServiceImpl.java
 *  @Class Name    : SendMailServiceImpl
 *  @Description   : 类描述
 *  @Author        : calonlan
 *  @Creation Date : 2015年3月27日 上午9:18:08
 *  @ModificationHistory
 *  Who        When          What r
 *  --------   ----------    -----------------------------------
 *  username   2015年3月27日       TODO
 */
@Service
@Transactional(readOnly = true)
public class SendMailServiceImpl implements SendMailService{
	private static final Logger logger = LoggerFactory.getLogger(SendMailServiceImpl.class);
	private boolean isSingle;

	@Override
	public void send(SendMessage message) {
		logger.info("[工作流程：发送邮件消息给相关人员]");
		MailSender sender = new MailSender(message);
		isSingle = true;
		sender.start();

	}


	@Override
	public void send(SendMessage[] messages) {
		logger.info("[工作流程：发送邮件消息给相关人员]");
		MailSender sender = new MailSender(messages);
		isSingle = false;
		sender.start();

	}

	class MailSender extends Thread {
		private SendMessage message;
		private SendMessage[] messages;

		public MailSender(SendMessage message) {
			this.message = message;
		}

		public MailSender(SendMessage[] messages) {
			this.messages = messages;
		}

		@Override
		public void run() {
			JavaMailSenderImpl mailSender = (JavaMailSenderImpl) BeanFactory.getBean("mailSender");
			//建立邮件信息
			MimeMessage mailMessage = mailSender.createMimeMessage();
			//String senderNickName = AppContext.getProperties("senderNickName");
			IdentityService identityService =
					IdFactory.getIdentityServiceFactory().getIdentityService();

			try {
				MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");
				if (isSingle) {
					User user = identityService.getUserById(message.getToUserId());
					if(StringUtils.isNotBlank(user.getEmail())){
						messageHelper.setTo(user.getEmail());
						messageHelper.setFrom(mailSender.getUsername());
						messageHelper.setSubject(message.getSubject());
						messageHelper.setText(message.getContent(),true);
						mailSender.send(mailMessage);
					}
				} else {
					for (SendMessage temp : messages) {
						messageHelper.setFrom(mailSender.getUsername());
						messageHelper.setSubject(temp.getSubject());
						messageHelper.setText(temp.getContent(),true);
						User user = identityService.getUserById(temp.getToUserId());
						if(StringUtils.isNotBlank(user.getEmail())){
							messageHelper.setTo(user.getEmail());
							mailSender.send(mailMessage);
						}
					}
				}
			} catch (MessagingException e) {
				logger.info("[工作流程：发送邮件消息出错]");
				e.printStackTrace();
			}

		}

	}

}
